//格式化时间
function dateFtt(fmt,date)   
{ //author: meizz   
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
} 
function formatSubscribeTime(cellValue, options, rowObject) {
	var dateStr = "";
	if(cellValue){
		var crtTime = new Date(cellValue);
		dateStr = dateFtt("yyyy-MM-dd hh:mm:ss",crtTime);
	}
    return dateStr;
}
//加载字典
function dictJudge(value, options, row){
    //sex为自定义字典项
	var statusObj = vm.options.sex;
    for( var i=0;i< statusObj.length;i++ ){
        if(statusObj[i].value == value){
            return '<span>'+statusObj[i].text+'</span>' ;
        }
    }
}

function getRootPath(){
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return(localhostPaht+projectName);
}


$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'news/ad/list',
        datatype: "json",
        colModel: [			
			{ label: 'ID号', name: 'id', index: 'id', width: 15, key: true },
			{ label: '广告名称', name: 'name', index: 'name'},
			{ label: '广告类型', name: 'type', index: 'type', width: 25,
                formatter: function (cellvalue, options, rowObject) {
                    return cellvalue == 1 ? "新闻内容公告页" : cellvalue == 2 ? "新闻内容内容页":cellvalue == 3 ? "出行服务页":"交警在线页";
                }
			},
			{ label: '编辑方式', name: 'editmode', index: 'editmode', width: 20,
                formatter: function (cellvalue, options, rowObject) {
                    return cellvalue == 1 ? "外部链接" : cellvalue == 2 ? "公告关联":"自编辑";
                }
			}
			// { label: '', name: 'content', index: 'content', width: 80 },
			// { label: '', name: 'createtime', index: 'createtime', width: 80 },
			// { label: '', name: 'updatatime', index: 'updatatime', width: 80 },
			// { label: '', name: 'imageurl', index: 'imageurl', width: 80 },
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});



var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			adType: '',
			editmode:'',
			adName: '',
            channel:''
		},
		viewType:'dataList',//显示页面类型
		// selected:'',

		//显示页面
		showList: true,
        addExtLinkADView: false,
        addInternalNoticeView: false,
        addEditADView: false,
        topicShowList:false,

		title: null,
		ad: {
			type:'',
            editType:'',
            imageurl:''
		},

        channels:{}
	},
	methods: {
		query: function () {
			vm.reload();
		},
        reset: function(){
            vm.q.adName = '';
            vm.q.adType = '';
            vm.q.editmode = '';
            vm.q.editmod = '';
            vm.reload();
        },

        queryTopic: function(){
            var page = $("#jqGrid_topic").jqGrid('getGridParam','page');
            $("#jqGrid_topic").jqGrid('setGridParam',{
                postData:{'cname': vm.q.channel},
                page:page
            }).trigger("reloadGrid");
        },

        addExtLinkAD: function(){
            vm.showList = false;
            vm.addExtLinkADView = true;
            // vm.viewType = 'addExtLinkADView';
            vm.title = "新增外部链接广告";
            vm.ad = {};
            vm.ad.editmode = '1';

            //清除
            $("#myFile1").fileinput('clear');
            //清除
            $('#myFile1').fileinput('destroy');
            //广告图片
            $("#myFile1").fileinput({
                language : 'zh',
                uploadUrl : baseURL + "common/file/upload/saveFile",
                // uploadUrl : "${request.contextPath}/ueditor/upload/photo",
                autoReplace : true,
                showUpload: false,
                maxFileCount : 1,
                allowedFileExtensions : [ "jpg", "png", "gif" ],
                browseClass : "btn btn-primary", //按钮样式
                browseLabel: "上传",
                previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
                layoutTemplates:{
                    actionUpload:'',//去除上传预览缩略图中的上传图片
                    // actionZoom:'',   去除上传预览缩略图中的查看详情预览的缩略图标
                    // actionDownload:'', //去除上传预览缩略图中的下载图标
                    actionDelete:'', //去除上传预览的缩略图中的删除图标
                }
            }).on("filebatchselected", function(event, files) {
                $(this).fileinput("upload");
            }).on("fileuploaded", function(e, data) {
                var res = data.response;
                /* alert(res.success); */
                // document.getElementById("alogo").value=res.success;
                // vm.ad.imageurl = res.success;
                vm.ad.imageurl = res.fileList[0].url;
            });
        },


        addInternalNotice:function(){
            vm.showList = false;
            vm.addInternalNoticeView = true;

            vm.title = "新增内部公告关联";
            vm.ad = {};
            vm.ad.editmode = '2';
            //清除
            $("#myFile2").fileinput('clear');
            //清除
            $('#myFile2').fileinput('destroy');
            //广告图片
            $("#myFile2").fileinput({
                language : 'zh',
                uploadUrl : baseURL + "common/file/upload/saveFile",
                // uploadUrl : "${request.contextPath}/ueditor/upload/photo",
                autoReplace : true,
                showUpload: false,
                maxFileCount : 1,
                allowedFileExtensions : [ "jpg", "png", "gif" ],
                browseClass : "btn btn-primary", //按钮样式
                browseLabel: "上传",
                previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
                layoutTemplates:{
                    actionUpload:'',//去除上传预览缩略图中的上传图片
                    // actionZoom:'',   去除上传预览缩略图中的查看详情预览的缩略图标
                    // actionDownload:'', //去除上传预览缩略图中的下载图标
                    actionDelete:'', //去除上传预览的缩略图中的删除图标
                }
            }).on("filebatchselected", function(event, files) {
                $(this).fileinput("upload");
            }).on("fileuploaded", function(e, data) {
                var res = data.response;
                /* alert(res.success); */
                // document.getElementById("alogo").value=res.success;
                // vm.ad.imageurl = res.success;
                vm.ad.imageurl = res.fileList[0].url;
            });
        },

        addEditAD:function(){
            vm.showList = false;
            vm.addEditADView = true;

            vm.title = "新增自编辑广告";
            vm.ad = {};
            vm.ad.editmode='3';

            function getRootPath(){
                //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
                var curWwwPath=window.document.location.href;
                //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
                var pathName=window.document.location.pathname;
                var pos=curWwwPath.indexOf(pathName);
                //获取主机地址，如： http://localhost:8083
                var localhostPaht=curWwwPath.substring(0,pos);
                //获取带"/"的项目名，如：/uimcardprj
                var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
                return(localhostPaht+projectName);
            }
            //富文本编辑器--发布内容
            // var ue = UE.getEditor('editor');
            UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
            UE.Editor.prototype.getActionUrl = function(action) {
                if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage'
                    || action == 'uploadvideo' || action == 'uploadfile') {
                    // return '${pageContext.request.contextPath}/ueditor/upload';
                    return getRootPath() + '/common/file/upload/ueSaveFile';
                }else {
                    return this._bkGetActionUrl.call(this, action);
                }
            };

            //清除
            $("#myFile3").fileinput('clear');
            //清除
            $('#myFile3').fileinput('destroy');
            //广告图片
            $("#myFile3").fileinput({
                language : 'zh',
                uploadUrl : baseURL + "common/file/upload/saveFile",
                // uploadUrl : "${request.contextPath}/ueditor/upload/photo",
                autoReplace : true,
                showUpload: false,
                maxFileCount : 1,
                allowedFileExtensions : [ "jpg", "png", "gif" ],
                browseClass : "btn btn-primary", //按钮样式
                previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
                layoutTemplates:{
                    actionUpload:'',//去除上传预览缩略图中的上传图片
                    // actionZoom:'',   去除上传预览缩略图中的查看详情预览的缩略图标
                    // actionDownload:'', //去除上传预览缩略图中的下载图标
                    actionDelete:'', //去除上传预览的缩略图中的删除图标
                }
            }).on("filebatchselected", function(event, files) {
                $(this).fileinput("upload");
            }).on("fileuploaded", function(e, data) {
                var res = data.response;
                /* alert(res.success); */
                // document.getElementById("alogo").value=res.success;
                console.log("before-res.fileList[0].url:"+JSON.stringify(res.fileList[0].url))
                vm.ad.imageurl = res.fileList[0].url;
                console.log("after-vm.ad.imageurl:"+JSON.stringify(vm.ad.imageurl))
                // vm.ad.imageurl = res.success;
            });
        },

        //新增内部公告关联页面中添加关联的新闻ID
        addlink:function(){
            vm.addInternalNoticeView = false;
            vm.topicShowList = true;
            vm.getChannels();
            $(function () {
                $("#jqGrid_topic").jqGrid({
                    url: baseURL + 'news/topic/list',
                    datatype: "json",
                    colModel: [
                        { label: '序号', name: 'id', index: 'id', width: 15, key: true },
                        { label: '编辑者', name: 'author', index: 'author', width: 25 },
                        { label: '公告类型', name: 'cname', index: 'cname', width: 25 },
                        { label: '发布时间', name: 'publishDate', index: 'publish_date', width: 30,
                            formatter:
                                function(cellvalue, options, row){
                                    return dateFtt("yyyy-MM-dd",new Date(cellvalue))
                                }
                        },
                        { label: '发布状态', name: 'status', index: 'status', width: 25,
                            formatter: function (cellvalue, options, rowObject) {
                                return cellvalue == 1 ? "已发布" : "未发布";
                            }
                        },
                        { label: '标题', name: 'title', index: 'title'}
                    ],
                    viewrecords: true,
                    height: 385,
                    rowNum: 10,
                    rowList : [10,30,50],
                    rownumbers: true,
                    rownumWidth: 25,
                    // autowidth:true,
                    multiselect: true,
                    pager: "#jqGridPager_topic",
                    jsonReader : {
                        root: "page.list",
                        page: "page.currPage",
                        total: "page.totalPage",
                        records: "page.totalCount"
                    },
                    prmNames : {
                        page:"page",
                        rows:"limit",
                        order: "order"
                    },
                    gridComplete:function(){
                        //隐藏grid底部滚动条
                        $("#jqGrid_topic").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                    }
                });
            });
        },

        //link
        link: function(){
		    var id = getSelectedTopic("jqGrid_topic");
            if(id == null){
                return ;
            }
            vm.topicShowList = false;
            vm.addInternalNoticeView = true;
            $("#linkedTopicId").text(id);
            vm.ad.content=id;

            // $("#jqGrid_topic").trigger("reloadGrid");
        },

        //获取所有公告类型
        getChannels: function(){
            $.get(baseURL + "news/channel/list", function(r){
                vm.channels = r.page.list;

            });
        },

		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id);

		},
		saveOrUpdate: function (event) {
			var url = vm.ad.id == null ? "news/ad/save" : "news/ad/update";

			//外部链接
            if (vm.ad.editmode==1){

            }

            //内部公告关联
            if (vm.ad.editmode==2){

            }

            //自编辑广告
            if (vm.ad.editmode==3){
                // var ue = UE.getEditor('editor');
                vm.ad.content =encodeURI(ue.getContent());
            }

			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.ad),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "news/ad/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},

        //获取所有公告类型
        getChannels: function(){
            $.get(baseURL + "news/channel/list", function(r){
                vm.channels = r.page.list;

            });
        },

		getInfo: function(id){
            $.ajaxSettings.async = false;
			$.get(baseURL + "news/ad/info/"+id, function(r){
                vm.ad = r.ad;
                //外部链接广告
                console.log("getInfo2-----"+vm.ad.editmode);
                if (vm.ad.editmode==1){
                    vm.addExtLinkADView = true;
                    //清除
                    $("#myFile1").fileinput('destroy');
                    //手机缩略图
                    $("#myFile1").fileinput({
                        language : 'zh',
                        uploadUrl : baseURL + "common/file/upload/saveFile",
                        // uploadUrl : "${request.contextPath}/ueditor/upload/photo",
                        autoReplace : true,
                        showUpload: false,
                        maxFileCount : 1,
                        allowedFileExtensions : [ "jpg", "png", "gif" ],
                        browseClass : "btn btn-primary", //按钮样式
                        previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
                       /* initialPreview: [
                            "<img src="+vm.ad.imageurl+"class='file-preview-image'/>"],*/
                        initialPreview: function () {
                            var imageurl = vm.ad.imageurl;
                            if (imageurl===undefined || imageurl==null || imageurl===''){
                                return [];
                            }
                            return["<img src="+imageurl+" class='file-preview-image' style='height: 100%;' alt='logo'/>"]
                        }(),
                        layoutTemplates:{
                            actionUpload:'',//去除上传预览缩略图中的上传图片
                            // actionZoom:'',   去除上传预览缩略图中的查看详情预览的缩略图标
                            // actionDownload:'', //去除上传预览缩略图中的下载图标
                            actionDelete:'', //去除上传预览的缩略图中的删除图标
                        }
                    }).on("filebatchselected", function(event, files) {
                        $(this).fileinput("upload");
                    }).on("fileuploaded", function(e, data) {
                        var res = data.response;
                        /* alert(res.success); */
                        // vm.ad.imageurl=res.success;
                        vm.ad.imageurl = res.fileList[0].url;
                    }).on('filecleared', function() {
                        console.log('filecleared');
                        vm.ad.imageurl = '';
                        console.log(vm.ad);
                    });
                }
                //内部公告关联
                if (vm.ad.editmode==2){
                    vm.addInternalNoticeView = true;

                    // if (vm.ad.content !=null)
                    $("#linkedTopicId").text(vm.ad.content);

                    //清除
                    $("#myFile2").fileinput('destroy');

                    //手机缩略图
                    $("#myFile2").fileinput({
                        language : 'zh',
                        uploadUrl : baseURL + "common/file/upload/saveFile",
                        // uploadUrl : ctx+"/ueditor/upload/photo",
                        autoReplace : true,
                        showUpload: false,
                        maxFileCount : 1,
                        allowedFileExtensions : [ "jpg", "png", "gif" ],
                        browseClass : "btn btn-primary", //按钮样式
                        previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
                        /*initialPreview: [
                            "<img src="+vm.ad.imageurl+" class='file-preview-image'/>"],*/
                        initialPreview: function () {
                            var imageurl = vm.ad.imageurl;
                            if (imageurl===undefined || imageurl==null || imageurl===''){
                                return [];
                            }
                            return["<img src="+imageurl+" class='file-preview-image' style='height: 100%;' alt='logo'/>"]
                        }(),
                        layoutTemplates:{
                            actionUpload:'',//去除上传预览缩略图中的上传图片
                            // actionZoom:'',   去除上传预览缩略图中的查看详情预览的缩略图标
                            // actionDownload:'', //去除上传预览缩略图中的下载图标
                            actionDelete:'', //去除上传预览的缩略图中的删除图标
                        }
                    }).on("filebatchselected", function(event, files) {
                        $(this).fileinput("upload");
                    }).on("fileuploaded", function(e, data) {
                        var res = data.response;
                        /* alert(res.success); */
                        // vm.ad.imageurl=res.success;
                        vm.ad.imageurl = res.fileList[0].url;
                    }).on('filecleared', function() {
                        console.log('filecleared');
                        vm.ad.imageurl = '';
                        console.log(vm.ad);
                    });
                }
                //自编辑广告
                if (vm.ad.editmode==3){
                    vm.addEditADView = true;


                    //富文本--内容
                    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
                    UE.Editor.prototype.getActionUrl = function(action) {
                        if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage'
                            || action == 'uploadvideo' || action == 'uploadfile') {
                            // return '${request.contextPath}/ueditor/upload';
                            return getRootPath() + '/common/file/upload/ueSaveFile';
                        }else {
                            return this._bkGetActionUrl.call(this, action);
                        }
                    };
                    ue.ready(function(){//监听编辑器实例化完成的事件
                        ue.setContent("");
                        vm.ad.content = vm.ad.content.replace(/&amp;nbsp;/ig,' ');
                        ue.setContent(vm.ad.content );
                    });

                    //清除
                    $("#myFile3").fileinput('destroy');

                    //手机缩略图
                    $("#myFile3").fileinput({
                        language : 'zh',
                        uploadUrl : baseURL + "common/file/upload/saveFile",
                        // uploadUrl : "${request.contextPath}/ueditor/upload/photo",
                        autoReplace : true,
                        showUpload: false,
                        maxFileCount : 1,
                        allowedFileExtensions : [ "jpg", "png", "gif" ],
                        browseClass : "btn btn-primary", //按钮样式
                        previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
                       /* initialPreview: [
                            "<img src="+vm.ad.imageurl+" class='file-preview-image'/>"],*/
                        initialPreview: function () {
                            var imageurl = vm.ad.imageurl;
                            if (imageurl===undefined || imageurl==null || imageurl===''){
                                return [];
                            }
                            return["<img src="+imageurl+" class='file-preview-image' style='height: 100%;' alt='logo'/>"]
                        }(),
                        layoutTemplates:{
                            actionUpload:'',//去除上传预览缩略图中的上传图片
                            // actionZoom:'',   去除上传预览缩略图中的查看详情预览的缩略图标
                            // actionDownload:'', //去除上传预览缩略图中的下载图标
                            actionDelete:'', //去除上传预览的缩略图中的删除图标
                        }
                    }).on("filebatchselected", function(event, files) {
                        $(this).fileinput("upload");
                    }).on("fileuploaded", function(e, data) {
                        var res = data.response;
                        /* alert(res.success); */
                        // vm.ad.imageurl=res.success;
                        vm.ad.imageurl = res.fileList[0].url;
                    }).on('filecleared', function() {
                        console.log('filecleared');
                        vm.ad.imageurl = '';
                        console.log(vm.ad);
                    });
                }


            });
            $.ajaxSettings.async = true;
			console.log("getInfo2-----"+vm.editmode);

		},

        reload: function (event) {
			vm.showList = true;
            vm.addExtLinkADView = false;
            vm.addInternalNoticeView = false;
            vm.addEditADView = false;
            ue.setContent("");

            console.log(vm.viewType);
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:
                	{'name': vm.q.adName,
					 'type': vm.q.adType,
                     'editmode': vm.q.editmode
					},
                page:page
            }).trigger("reloadGrid");
		},



        //关联公告返回
        backToInternalNotice: function () {
            $("#linkedTopicId").text("点击获取公众号关联");
            vm.topicShowList = false;
            vm.addInternalNoticeView = true;

        }
	}
});


//选择一条记录
function getSelectedTopic(g) {
    var grid = $("#"+g);
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
        alert("请选择一条记录");
        return ;
    }

    var selectedIDs = grid.getGridParam("selarrrow");
    if(selectedIDs.length > 1){
        alert("只能选择一条记录");
        return ;
    }
    return selectedIDs[0];

}